package com.sinvo.oa.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sinvo.oa.entity.model.system.SysUser;
import com.sinvo.oa.entity.vo.wechat.BindPhoneVo;
import com.sinvo.oa.exception.CustomException;
import com.sinvo.oa.result.R;
import com.sinvo.oa.result.ResultCode;
import com.sinvo.oa.service.SysUserService;
import com.sinvo.oa.util.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;

/**
 * @Description 微信公众号控制器
 */
@Api(tags = "微信功能管理接口")
@Controller
@RequestMapping("admin/wechat")
@CrossOrigin
public class WechatController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private WxMpService wxMpService;

    @Value("${wechat.userInfoUrl}")
    private String userInfoUrl;

    /**
     * 进入时调用 授权方法
     * @param returnUrl
     * @return
     */
    @GetMapping("authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl) {
        //param1:授权路径 在哪个路径获取微信信息
        //param2:固定值 授权类型
        //param3:授权成功跳转路径
        String redirectUrl = wxMpService.getOAuth2Service().buildAuthorizationUrl(userInfoUrl, WxConsts.OAuth2Scope.SNSAPI_BASE, URLEncoder.encode(returnUrl.replace("oa", "#")));
        System.out.println("authorize:"+redirectUrl);
        return "redirect:" + redirectUrl;
    }

    /**
     * 获取用户数据
     * @param code
     * @param returnUrl
     * @return
     * @throws Exception
     */
    @GetMapping("userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        //获取accessToken
        WxOAuth2AccessToken accessToken = wxMpService.getOAuth2Service().getAccessToken(code);
        //获取openId
        String openId = accessToken.getOpenId();
        System.out.println("openId:"+openId);
        //openid查询用户
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getOpenId, openId);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        String token = "";
        if (sysUser != null) {
            token = JwtUtils.createToken(sysUser.getId(), sysUser.getUsername());
        }
        if (returnUrl.indexOf("?") == -1) {
            System.out.println("userInfo1:"+"redirect:" + returnUrl + "?token=" + token + "&openId=" + openId);
            return "redirect:" + returnUrl + "?token=" + token + "&openId=" + openId;
        } else {
            System.out.println("userInfo2:"+"redirect:" + returnUrl + "&token=" + token + "&openId=" + openId);
            return "redirect:" + returnUrl + "&token=" + token + "&openId=" + openId;
        }
    }

    /**
     * 绑定手机
     * @param bindPhoneVo
     * @return
     */
    @ApiOperation(value = "微信账号绑定手机")
    @PostMapping("bindPhone")
    @ResponseBody
    public R bindPhone(@RequestBody BindPhoneVo bindPhoneVo) {
        //根据手机号查询
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getPhone, bindPhoneVo.getPhone());
        SysUser sysUser = sysUserService.getOne(queryWrapper);

        if (sysUser == null) {
            throw new CustomException(ResultCode.DATA_ERROR.getCode(), "手机号不存在，请联系管理员");
        }
        sysUser.setOpenId(bindPhoneVo.getOpenId());
        sysUserService.updateById(sysUser);
        String token = JwtUtils.createToken(sysUser.getId(), sysUser.getUsername());
        return R.success(token);
    }
}
